<template>
  <div style="width: 100%; height: 100%">
    <el-card class="box-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span>消息通知管理</span>
        <el-button type="primary" @click="createNotification" style="float: right; margin-left: 10px;">新增消息通知</el-button>
        <el-button type="danger" @click="batchDeleteNotifications" style="float: right;">批量删除</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="notificationList" ref="notificationTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="message" label="内容"></el-table-column>
        <el-table-column prop="created_at" label="发送日期"></el-table-column>
        <el-table-column label="接收人">
          <template slot-scope="scope">
            {{ watchStuName(scope.row.user_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="read_status" label="状态"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="editNotification(scope.row)" type="primary" size="small">编辑</el-button>
            <el-button @click="deleteNotification(scope.row)" type="danger" size="small">删除</el-button>
            <el-button @click="sendNotification(scope.row)" type="success" size="small">发送</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 消息通知弹窗 -->
    <el-dialog title="消息通知" :visible.sync="dialogVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
          <el-input v-model="form.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="内容" :label-width="formLabelWidth" prop="message">
          <el-input v-model="form.message" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="发送日期" :label-width="formLabelWidth" prop="interview_date">
          <el-date-picker v-model="form.interview_date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
        <el-form-item label="发送时间" :label-width="formLabelWidth" prop="interview_time">
          <el-time-picker v-model="form.interview_time" placeholder="选择时间" value-format="HH:mm:ss"></el-time-picker>
        </el-form-item>
        <el-form-item label="接收人" :label-width="formLabelWidth" prop="student_id">
          <el-select v-model="form.user_id" placeholder="请选择对象">
            <el-option v-for="item in StuOption" :key="item.user_id" :label="item.name" :value="item.user_id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      notificationList: [],
      dialogVisible: false,
      form: {
        notificationId: '',
        title: '',
        message: '',
        interview_date: '',
        interview_time: '',
        student_id: '',
        user_id: '',
        sender_id: '',
        read_status: 'unread',
      },
      formLabelWidth: '120px',
      selectedNotifications: [],
      StuOption: [],
      user: JSON.parse(localStorage.getItem('userData')) || {},
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        message: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        interview_date: [{ required: true, message: '请选择发送日期', trigger: 'change' }],
        interview_time: [{ required: true, message: '请选择发送时间', trigger: 'change' }],
        student_id: [{ required: true, message: '请输入接收人', trigger: 'blur' }],
      },
    };
  },
  created() {
    this.fetchNotifications();
    this.findStuList();
  },
  methods: {
    fetchNotifications() {
      axios.get('http://localhost:8080/api/notification/all')
          .then(response => {
            this.notificationList = response.data;
            // Format dates received from backend
            this.notificationList.forEach(notification => {
              notification.created_at = new Date(notification.created_at).toISOString().split('T')[0]; // Format date as yyyy-MM-dd
            });
          })
          .catch(error => {
            console.error('Error fetching notifications:', error);
          });
    },
    findStuList() {
      axios.get("http://localhost:8080/api/notification/findStuList")
          .then(response => {
            this.StuOption = response.data;
          });
    },
    createNotification() {
      this.resetForm();
      this.dialogVisible = true;
    },
    editNotification(row) {
      // Populate the form for editing
      this.form = { ...row };
      this.dialogVisible = true;
    },
    watchStuName(user_id) {
      for (let user of this.StuOption) {
        if (user.user_id === user_id) {
          return user.name;
        }
      }
    },
    deleteNotification(row) {
      this.$confirm('确定删除该消息通知？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:8080/api/notification/delete/${row.notification_id}`)
            .then(() => {
              this.fetchNotifications();
              this.$message({
                message: '消息通知已删除',
                type: 'success'
              });
            })
            .catch(error => {
              console.error('Error deleting notification:', error);
            });
      }).catch(() => {
        // do nothing if canceled
      });
    },
    batchDeleteNotifications() {
      if (this.selectedInterviews.length === 0) {
        this.$message.warning('请选择要删除的消息通知');
        return;
      }

      this.$confirm('确定删除选中的消息通知？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(this.selectedInterviews)
        // const selectedIds = this.selectedNotifications.map(notification => notification.notification_id);
        axios.delete('http://localhost:8080/api/notification/batch-delete', { data: this.selectedInterviews })
            .then(() => {
              this.fetchNotifications();
              this.selectedNotifications = [];
              this.$message({
                message: '选中的消息通知已删除',
                type: 'success'
              });
            })
            .catch(error => {
              console.error('Error deleting selected notifications:', error);
            });
      }).catch(() => {
        // do nothing if canceled
      });
    },
    submitForm() {
      if (!this.form.notification_id) {
        // Adding a new notification
        this.form.sender_id = this.user.user_id;
        axios.post('http://localhost:8080/api/notification/add', this.form)
            .then(() => {
              this.$message({
                message: '消息通知已保存',
                type: 'success'
              });
              this.dialogVisible = false;
              this.fetchNotifications();
              this.resetForm();
            })
            .catch(error => {
              console.error('Error saving notification:', error);
            });
      } else {
        // Updating an existing notification
        axios.put('http://localhost:8080/api/notification/update', this.form)
            .then(() => {
              this.$message({
                message: '消息通知已更新',
                type: 'success'
              });
              this.dialogVisible = false;
              this.fetchNotifications();
              this.resetForm();
            })
            .catch(error => {
              console.error('Error updating notification:', error);
            });
      }
    },
    resetForm() {
      this.form = {
        notificationId: '',
        title: '',
        message: '',
        interview_date: '',
        interview_time: '',
        student_id: '',
        user_id: '',
        sender_id: '',
        read_status: 'unread',
      };
    },
    handleSelectionChange(val) {
      this.selectedInterviews = val.map(row => row.notification_id);
    },
    // handleSelectionChange(selection) {
    //   this.selectedNotifications = selection;
    // },
    // Dummy function for sending notification (to be implemented)
    sendNotification(row) {
      this.$message({
        message: '通知已发送',
        type: 'success'
      });
    }
  }
};
</script>

<style scoped>
/* Add your scoped styles here */
</style>
